<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body></body>
  <script>
    // 创建一个类
    function Sale(price) {
      this.price = price; //这里的price是税前价格
      this.decorators_list = []; //添加一个属性，用来存放装饰器
    }

    // 为类添加用于添加装饰器的方法
    Sale.prototype.decorate = function (decorate) {
      this.decorators_list.push(decorate);
    };

    // 创建一个用来存放装饰器的对象
    Sale.decorators = {};

    // 创建装饰器1
    Sale.decorators.centralTax = {
      //国税
      getPrice: function (price) {
        return price * 1.05; //国税增加5%的税收
      },
    };
    // 创建装饰器2
    Sale.decorators.localTax = {
      //地税
      getPrice: function (price) {
        return price * 1.075; //地税增加7.5%的税收
      },
    };
    // 创建装饰器3
    Sale.decorators.finalPrice = {
      //最终价格
      getPrice: function (price) {
        return "￥" + price.toFixed(2); //保留两位小数且转换为文本型
      },
    };

    // 完成装饰器的调用（使用）
    Sale.prototype.getPrice = function () {
      var price = this.price; //税前价格
      var dLen = this.decorators_list.length; //获取装饰器个数
      console.log("初始定价：￥" + price, "装饰器的个数为：" + dLen);
      // 循环调用装饰器并执行其方法
      for (var i in this.decorators_list) {
        var name = this.decorators_list[i];
        console.log(name);
        price = Sale.decorators[name].getPrice(price);
      }
      console.log("计算国税和地税后最终价格为：" + price);
      return price;
    };

    var goods = new Sale(50000);
    goods.decorate("centralTax"); //添加装饰器到decorators_list
    goods.decorate("localTax");
    goods.decorate("finalPrice");

    var payment = goods.getPrice();
    console.log("您应该支付税后的价格为：" + payment);
  </script>
</html>
